package com.xjnt.frameworks.plugin.quartz;

import java.util.List;

import org.quartz.Job;

import com.google.common.collect.Lists;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log4jLogger;
import com.jfinal.log.Logger;
import com.jfinal.plugin.IPlugin;
import com.xjnt.frameworks.annotation.QJob;
import com.xjnt.frameworks.utils.ClasserKit;

/**
 * 定时任务调度插件
 * @author CAOYONG
 *
 */
public class QuartzPlugin implements IPlugin {


	private static final Logger logger = Log4jLogger.getLogger(QuartzPlugin.class);
	
	private boolean isStarted = false;
	
	/**
	 * 是否解析Library库中的所有Jar包
	 */
	private boolean includeAllJarsInLib = false;
	
	/**
	 * 需要解析的Jar包路径集合
	 */
	private List<String> includeJars = Lists.newArrayList();
	
	/**
	 * 需要扫描的包路径集合
	 */
	private List<String> scanPackages = Lists.newArrayList();
	
	public QuartzPlugin addScanPackages(List<String> packages) {
		if(null != packages && !packages.isEmpty()){
			scanPackages.addAll(packages);
		}
		return this;
	}
	
	public QuartzPlugin addScanPackages(String... packages) {
		for (String pkg : packages) {
			scanPackages.add(pkg);
		}
		return this;
	}
	
	public QuartzPlugin addIncludeJars(String... jars) {
		for (String jar : jars) {
			includeJars.add(jar);
		}
		return this;
	}
	
	@Override
	public boolean start() {
		if(isStarted){
			return true;
		}
		List<Class<? extends Job>> jobClasses = ClasserKit.of(Job.class)
				.scanPackages(scanPackages).includeAllJarsInLib(includeAllJarsInLib).injars(includeJars)
				.search();
		QJob qJob;
		for (Class<? extends Job> clazz : jobClasses) {
			qJob = clazz.getAnnotation(QJob.class);
			if(qJob == null){
				logger.debug("QuartzKit.addJob:" + clazz.getName() + " not found annotation QJob.");
				continue;
			} else {
				boolean isUse = qJob.isUse();
				if(isUse){
					String jobName = qJob.name();
					String triggerName = qJob.triggerName();
					String cronExpress = qJob.cronExpression();
					String description = qJob.description();
					if(StrKit.notBlank(jobName) && StrKit.notBlank(triggerName) && StrKit.notBlank(cronExpress)){
						QJobStore store = new QJobStore(jobName, triggerName, cronExpress, description, clazz);
						QuartzKit.addQJobStore(jobName, store);
						logger.debug("QuartzKit.addJob(" + jobName + ", " + clazz.getName() + ")");
					} else {
						logger.debug("QuartzKit.addJob:" + clazz.getName() + " QJob annotation information is incomplete.");
					}
				}
			}
		}
		QuartzKit.start();
		return true;
	}

	@Override
	public boolean stop() {
		QuartzKit.shutdownAll();
		scanPackages.clear();
		return true;
	}

}
